import { defineStore } from 'pinia'
import { getMenuByRole } from '@/api/menu'

export const useUserStore = defineStore('user', {
  state: () => ({
    // 用户信息
    userInfo: {
      id: null,
      username: '',
      nickname: '',
      avatar_url: '',
      email: '',
      phone_number: '',
      gender: 0,
      status: 0
    },
    // 用户角色
    role: 'Student', // Student, ClubAdmin, SuperAdmin
    // 权限菜单
    menuList: [],
    // 登录状态
    isLoggedIn: false,
    // 加载状态
    loading: false
  }),

  getters: {
    // 获取用户显示名称
    displayName: (state) => {
      return state.userInfo.nickname || state.userInfo.username
    },
    
    // 获取用户头像
    avatar: (state) => {
      return state.userInfo.avatar_url || 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
    },
    
    // 检查是否为管理员
    isAdmin: (state) => {
      return state.role === 'ClubAdmin' || state.role === 'SuperAdmin'
    },
    
    // 检查是否为超级管理员
    isSuperAdmin: (state) => {
      return state.role === 'SuperAdmin'
    }
  },

  actions: {
    // 设置用户信息
    setUserInfo(userInfo) {
      this.userInfo = { ...this.userInfo, ...userInfo }
    },

    // 设置用户角色
    setRole(role) {
      this.role = role
      this.updateMenuList()
    },

    // 更新菜单列表
    updateMenuList() {
      this.menuList = getMenuByRole(this.role)
    },

    // 登录
    async login(loginData) {
      this.loading = true
      try {
        // 模拟登录请求
        const response = await new Promise((resolve) => {
          setTimeout(() => {
            // 模拟不同角色的登录
            const mockUsers = {
              'student': {
                userInfo: {
                  id: 1,
                  username: 'student001',
                  nickname: '张三',
                  avatar_url: '',
                  email: 'student@example.com',
                  phone_number: '13800138001',
                  gender: 1,
                  status: 0
                },
                role: 'Student'
              },
              'admin': {
                userInfo: {
                  id: 2,
                  username: 'admin001',
                  nickname: '李四',
                  avatar_url: '',
                  email: 'admin@example.com',
                  phone_number: '13800138002',
                  gender: 1,
                  status: 0
                },
                role: 'ClubAdmin'
              },
              'super': {
                userInfo: {
                  id: 3,
                  username: 'super001',
                  nickname: '王五',
                  avatar_url: '',
                  email: 'super@example.com',
                  phone_number: '13800138003',
                  gender: 1,
                  status: 0
                },
                role: 'SuperAdmin'
              }
            }
            
            const userType = loginData.username.includes('super') ? 'super' : 
                           loginData.username.includes('admin') ? 'admin' : 'student'
            
            resolve({
              data: {
                token: 'mock-token-' + Date.now(),
                user: mockUsers[userType]
              }
            })
          }, 1000)
        })

        // 保存token和用户信息
        localStorage.setItem('token', response.data.token)
        localStorage.setItem('userInfo', JSON.stringify(response.data.user.userInfo))
        
        // 设置用户信息
        this.setUserInfo(response.data.user.userInfo)
        this.setRole(response.data.user.role)
        this.isLoggedIn = true
        
        return response.data
      } catch (error) {
        throw error
      } finally {
        this.loading = false
      }
    },

    // 登出
    async logout() {
      try {
        // 清除本地存储
        localStorage.removeItem('token')
        localStorage.removeItem('userInfo')
        
        // 重置状态
        this.userInfo = {
          id: null,
          username: '',
          nickname: '',
          avatar_url: '',
          email: '',
          phone_number: '',
          gender: 0,
          status: 0
        }
        this.role = 'Student'
        this.menuList = []
        this.isLoggedIn = false
        
        return true
      } catch (error) {
        throw error
      }
    },

    // 初始化用户信息（从本地存储恢复）
    initUserInfo() {
      const token = localStorage.getItem('token')
      const userInfo = localStorage.getItem('userInfo')
      
      if (token && userInfo) {
        try {
          const parsedUserInfo = JSON.parse(userInfo)
          this.setUserInfo(parsedUserInfo)
          this.isLoggedIn = true
          
          // 根据用户信息确定角色（这里简化处理）
          if (parsedUserInfo.username.includes('super')) {
            this.setRole('SuperAdmin')
          } else if (parsedUserInfo.username.includes('admin')) {
            this.setRole('ClubAdmin')
          } else {
            this.setRole('Student')
          }
        } catch (error) {
          console.error('Failed to parse user info:', error)
          this.logout()
        }
      }
    }
  }
})
